<template>
    <div class="personal-info">
        <el-breadcrumb separator="/" class="header">
            <el-breadcrumb-item>个人信息</el-breadcrumb-item>
        </el-breadcrumb>

        <div class="avatar-group">
            <el-upload class="avatar-uploader" action="#" :http-request="handleAvatarUpload" :show-file-list="false"
                :before-upload="beforeAvatarUpload" accept=".jpg,.jpeg,.png">
                <el-avatar :src="avatarUrl" class="current-avatar" style="background-color: #eee; color: #666;"
                    @mouseenter="showEditTip = true" @mouseleave="showEditTip = false">
                    {{ showEditTip ? '修改头像' : '' }}
                </el-avatar>
            </el-upload>
            <p class="avatar-desc">推荐840x840像素，JPG/PNG,5M以内。头像修改后，部分页面次日生效。</p>
        </div>

        <el-form ref="formRef" :model="form" :rules="formRules" label-width="80px" class="info-form">
            <el-form-item label="账号" prop="userName">
                <el-input v-model="form.userName" disabled />
                <div class="form-desc">账号信息用于登录,系统不允许修改</div>
            </el-form-item>

            <el-form-item label="姓名" prop="nickName">
                <el-input v-model="form.nickName" disabled />
            </el-form-item>

            <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="form.sex">
                    <el-radio label="0">男</el-radio>
                    <el-radio label="1">女</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="手机号" prop="phonenumber">
                <el-input v-model="form.phonenumber" />
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" />
            </el-form-item>

            <el-form-item label="所属角色" prop="role">
                <el-input v-model="form.role" disabled />
            </el-form-item>
        </el-form>

        <div class="form-footer">
            <el-button type="primary" @click="handleSubmit">确定</el-button>
            <el-button @click="handleCancel">取消</el-button>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useAuthStore } from '../../../stores/auth';
import { getProfile, updateProfile, uploadAvatar } from '../../../api/auth';

const authStore = useAuthStore();
const formRef = ref(null);
const showEditTip = ref(false);

const formRules = ref({
    nickName: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { max: 20, message: '姓名长度不能超过20个字符', trigger: 'blur' }
    ],
    phonenumber: [
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
    ],
    email: [
        {
            pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
            message: '请输入正确的邮箱格式',
            trigger: 'blur'
        }
    ],
    sex: [
        { required: true, message: '请选择性别', trigger: 'change' }
    ]
});

const form = ref({
    userName: authStore.userInfo.userName,
    nickName: authStore.userInfo.nickName,
    sex: authStore.userInfo.sex,
    phonenumber: authStore.userInfo.phonenumber,
    email: authStore.userInfo.email,
    role: authStore.roleGroup
});

const avatarUrl = computed(() => {
    if (authStore.userInfo && authStore.userInfo.avatar) {
        return authStore.userInfo.avatar;
    }
    return ''
});

onMounted(async () => {
    try {
        const res = await getProfile();
        console.log('获取用户信息响应:', res);

        if (res && res.code === 200) {
            const newUserInfo = res.data;
            const newRoleGroup = res.roleGroup;

            const isUserInfoChanged = JSON.stringify(newUserInfo) !== JSON.stringify(authStore.userInfo);
            const isRoleGroupChanged = newRoleGroup !== authStore.roleGroup;

            if (isUserInfoChanged || isRoleGroupChanged) {
                authStore.setUserInfo({ data: newUserInfo, roleGroup: newRoleGroup });
                console.log('authStore 数据更新（因数据变化）');
            }

            form.value = {
                userName: newUserInfo.userName,
                nickName: newUserInfo.nickName,
                sex: newUserInfo.sex,
                phonenumber: newUserInfo.phonenumber,
                email: newUserInfo.email,
                role: newRoleGroup
            };
        } else {
            const errorMsg = res?.msg || '未知错误';
            ElMessage.error(`获取用户信息失败：${errorMsg}`);
        }
    } catch (err) {
        ElMessage.error('获取用户信息异常，请稍后重试');
        console.error('用户信息拉取失败：', err);
    }
});

const beforeAvatarUpload = (file) => {
    const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isImage) {
        ElMessage.error('仅支持JPG/PNG格式的图片！');
        return false;
    }
    const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isLt5M) {
        ElMessage.error('图片大小不能超过5MB！');
        return false;
    }
    return new Promise((resolve) => {
        const img = new Image();
        img.onload = () => {
            const { width, height } = img;
            if (width !== 840 || height !== 840) {
                ElMessage.warning('推荐上传840x840像素的图片，尺寸不符可能影响显示效果');
            }
            resolve(true);
        };
        img.src = URL.createObjectURL(file);
    });
};

const handleAvatarUpload = async (uploadOpt) => {
    try {
        if (!uploadOpt || typeof uploadOpt !== 'object') {
            throw new Error('上传参数异常');
        }

        const file = uploadOpt.file;
        if (!file) {
            throw new Error('未获取到上传文件');
        }

        console.log('准备上传头像，文件信息:', file);
        const formData = new FormData();
        formData.append('avatarfile', file);

        ElMessage({
            message: '正在上传头像...',
            type: 'info',
            duration: 0,
            showClose: true
        });

        const res = await uploadAvatar(formData);
        console.log('头像上传接口响应:', res);

        ElMessage.closeAll();

        if (!res) {
            throw new Error('上传接口未返回数据');
        }

        if (res.code === 200) {
            ElMessage.success('头像上传成功！');
            if (res.imgUrl) {
                authStore.userInfo.avatar = res.imgUrl;
            } else {
                ElMessage.warning('头像信息格式异常');
            }
            if (typeof uploadOpt.onSuccess === 'function') {
                uploadOpt.onSuccess(res);
            }
        } else {
            const errorMsg = res.msg || '操作失败';
            ElMessage.error(`头像上传失败：${errorMsg}`);
            console.error('头像上传失败:', res);
            if (typeof uploadOpt.onError === 'function') {
                uploadOpt.onError(errorMsg);
            }
        }
    } catch (err) {
        ElMessage.closeAll();
        const errorMsg = err.message || '操作失败';
        ElMessage.error(`头像上传异常：${errorMsg}`);
        if (typeof uploadOpt.onError === 'function') {
            uploadOpt.onError(errorMsg);
        }
        console.error('头像上传失败：', err);
    }
};

const handleSubmit = async () => {
    try {
        await formRef.value.validate();
        const submitData = {
            nickName: form.value.nickName,
            sex: form.value.sex,
            phonenumber: form.value.phonenumber,
            email: form.value.email
        };

        console.log('准备提交的用户信息:', submitData);

        ElMessage({
            message: '正在保存信息...',
            type: 'info',
            duration: 0,
            showClose: true
        });

        const res = await updateProfile(submitData);
        console.log('信息更新接口响应:', res);

        ElMessage.closeAll();

        if (res && res.code === 200) {
            ElMessage.success('个人信息修改成功！');
            authStore.userInfo = { ...authStore.userInfo, ...submitData };
        } else {
            const errorMsg = res?.msg || '操作失败';
            ElMessage.error(`修改失败：${errorMsg}`);
            console.error('信息修改失败:', res);
        }
    } catch (err) {
        ElMessage.closeAll();
        if (err.name === 'Error') {
            const errorMsg = err.message || '操作失败';
            ElMessage.error(`修改信息异常：${errorMsg}`);
            console.error('信息修改失败：', err);
        }
    }
};

const handleCancel = () => {
    formRef.value.resetFields();
    const userInfo = authStore.userInfo;
    form.value = {
        userName: userInfo.userName,
        nickName: userInfo.nickName,
        sex: userInfo.sex,
        phonenumber: userInfo.phonenumber,
        email: userInfo.email,
        role: authStore.roleGroup
    };
};
</script>

<style scoped>
.personal-info {
    width: 100%;
    height: 100%;
    padding: 0 20px;
    box-sizing: border-box;
}

.header {
    padding: 15px 0;
    font-size: 20px;
    color: #333;
}

.avatar-group {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    margin-bottom: 24px;
    gap: 8px;
}

.avatar-uploader {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    gap: 8px;
}

.current-avatar {
    width: 120px;
    height: 120px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s;
    font-size: 14px;
}

.avatar-desc {
    font-size: 12px;
    color: #999;
    margin: 0;
}

.info-form {
    max-width: 600px;
}

.form-desc {
    font-size: 12px;
    color: #999;
    margin-top: 6px;
}

.form-footer {
    padding: 15px 0;
    max-width: 600px;
    display: flex;
    gap: 10px;
}
</style>
